<?php

namespace Leikes\Utils\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;
use Workerman\Lib\Timer;
use Leikes\Utils\Socket\SocketBindConfig;

class WebSocketCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'leikes:websocket {action} {-d?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '开启websocket服务。';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->bindExample = app(\App\Sockets\SocketBindConfig::class);
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        global $argv;
        $arg = $this->argument('action');
        $argv[1] = $argv[2];
        $argv[2] = isset($argv[3]) ? "-{$argv[3]}" : '';

        switch($arg){
            case 'start':
                $this->start();
                break;
            case 'stop':
                $this->stop();
                break;
            case 'restart':
                $this->restart();
                break;
            case 'reload':
                $this->reload();
                break;
            default:
                echo '指令错误，不存在该指令';
                break;
        }
    }

    protected function start(){
        foreach ($this->bindExample->bind as $class) {
            $classExample = app($class);

            $classExample->start();
        }

        Worker::runAll();
    }

    protected function stop(){
        foreach ($this->bindExample->bind as $class) {
            $classExample = app($class);

            $classExample->stop();
        }

        Worker::runAll();
    }

    protected function restart(){
        foreach ($this->bindExample->bind as $class) {
            $classExample = app($class);

            $classExample->restart();
        }

        Worker::runAll();
    }

    protected function reload(){
        foreach ($this->bindExample->bind as $class) {
            $classExample = app($class);

            $classExample->reload();
        }

        Worker::runAll();
    }
}
